package org.poem;

import cn.hutool.core.thread.ThreadUtil;
import com.google.common.collect.Lists;
import org.poem.config.DefaultZkLockConfig;
import org.poem.lock.ZkDistributedLock;
import org.poem.utils.ConstantCorn;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.List;

@EnableScheduling
@SpringBootApplication
public class Lock4zkApplication  implements CommandLineRunner {
    private static final Logger logger = LoggerFactory.getLogger(Lock4zkApplication.class);
    static DefaultZkLockConfig config = new DefaultZkLockConfig();
    @Value("${server.port}")
    private Integer port;
    static {
        config.setZkServers("127.0.0.1:2181");
        config.setBasePath("/lock/");
    }
    private static final List<String> orderIds = Lists.newArrayList(
            "1402922429779324933",
            "1402922429779324931",
            "562906960801501209",
            "562906960801501210",
            "562906960801501211"
    );

    static final ZkDistributedLock lock = new ZkDistributedLock(config, "lock4zk");


    public static void main(String[] args) {
        SpringApplication.run(Lock4zkApplication.class, args);
    }

    /**
     * 自动任务执行
     */
    @Scheduled(cron = ConstantCorn.EVERY_1_SECOND)
    public void every1Second(){
        for (String orderId : orderIds) {
            boolean b = false;
            try {
                lock.setLockData(orderId);
                lock.setPort(port);
                b = lock.tryLock() ;
                if (b){
                    logger.info(port + " 获取到锁." + Thread.currentThread().getName());
                    try {
                        ThreadUtil.safeSleep(Math.random() * 2000 + 1000);
                    } catch (Exception e) {
                        logger.error(e.getMessage(), e);
                    }
                }else {
                    logger.info(port + " 没有获取到锁."+ Thread.currentThread().getName());
                }
            }catch (Exception e){
                e.printStackTrace();
            }finally {
               if (b){
                   logger.info(port + " 取消锁."+ Thread.currentThread().getName());
                   lock.unlock();
               }
            }
        }
    }

    @Override
    public void run(String... args) throws Exception {

    }
}
